package backtrack;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Solution39 {
    LinkedList<Integer> track = new LinkedList<>();
    List<List<Integer>> result = new LinkedList<>();
    int sum = 0;

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        backTrack(candidates,0,target);
        return result;
    }

    public void backTrack(int[] nums,int start,int target){

        //base case
        if (sum == target){
            result.add(new LinkedList<>(track));
            return;
        }

        if (sum > target){
            return;
        }

        for (int i = start; i < nums.length; i++) {
            //做出选择
            track.add(nums[i]);
            sum += nums[i];

            backTrack(nums, i,target);

            //撤销选择
            track.removeLast();
            sum -= nums[i];
        }
    }
}
